$().ready(() => {
//项目时间
  let curDate = new Date().toISOString();
  let sTime = $('#item-time-start');
  let fTime = $('#item-time-finish');
  let proStart, proEndTime;

  sTime.change(() => {
    if (sTime.val() < curDate) {
      sTime.val('');
      toolTip(0, '起始时间必须大于当前时间 :(')
    }
    proStart = new Date(sTime.val()).getTime() / 1000;
  })
  fTime.change(() => {
    if (sTime.val() === '') {
      fTime.val('');
      toolTip(0, '请先选择起始时间 :(')
    } else if (fTime.val() < sTime.val()) {
      fTime.val('');
      toolTip(0, '结束时间必须大于起始时间 :(')
    }
    proEndTime = new Date(fTime.val()).getTime() / 1000;
  })


//项目选项
  let optionArr = [];
  let addOption = $('#item-option');


  $('.add-option').click(function () {
    if (addOption.val().trim() !== '') {
      add(addOption.val())
      if (optionArr.length === 10) {
        addOption.css('display', 'none')
        $(this).css('display', 'none')
      } else if (optionArr.length >= 2) {
        $('#main ').css('height', 1024 + 63 * (optionArr.length - 2) + 'px');
      }
    } else {
      toolTip(0, '请填写项目选项 :(')
    }
  })

  function add(val) {
    let div = $(`<div>${val}</div>`)
    optionArr.push(addOption.val())
    addOption.val('').before(div)
  }

//添加项目图片
  let imgFile;
  $('#file').change(() => {
    $(".item-image img").css('display', 'block')
    $('.item-image div').css('display', 'none')
    let img = new FileReader();
    img.onload = function (evt) {
      $(".item-image img").attr("src", evt.target.result);
    };
    imgFile = $("#file").prop("files")[0];
    img.readAsDataURL(imgFile);
  })

  $("#submit").click(() => {
    console.log(optionArr)

    const formData = new FormData();
    formData.append('ProName', $('#item-Name').val());
    formData.append('ProContent', $('#item-message').val());
    formData.append('ProStart', proStart);
    formData.append('ProEndTime', proEndTime);
    formData.append('ProNum', $('#vote').val());
    formData.append('ProOpt', '[' + optionArr + ']');
    if (imgFile !== undefined) {
      formData.append('img', imgFile);
    }

    if (isEmpty()) {
      let addProject = FileInterceptor('/addProject', 'post', formData)
      if (addProject.code===200){
        toolTip(1,'添加投票成功');
        setTimeout(function (){
          window.location.href = '../../pages/adminIndex/adminIndex.html';
        },500)
      }else {
        toolTip(0,addProject.message)
      }
    } else {
      toolTip(0, '不得为空')
    }
  })

  function isEmpty() {
    let success = false;
    $('.content-left input,textarea').each(function () {
      if ($(this).val().trim() === '' || this.id === 'item-option') {
        success = false
        if (optionArr.length !== 0) {
          success = true
        } else {
          return false
        }
      } else {
        success = true
      }
    })
    return success;
  }
})

